<template>
  <div class="page-apply">
    <div class="page-form">
      <LlForm ref="form" title="事项跟进">
        <LlFormItem
          label="事项类型"
          filed="followUpTypeName"
          :value="form.followUpTypeName"
          :showArrow="false"
        />

        <LlFormItem
          :label="`${titlePrefix}时间`"
          filed="outDate"
          :value="outDate.length ? outDate.join(' 至 ') : null"
        >
          <template #icon>
            <Icon :name="DateIcon" />
          </template>
        </LlFormItem>

        <LlFormItem
          v-if="form.followUpType !== 3"
          :label="`${titlePrefix}商机`"
          filed="businessOpportunityName"
          :value="form.businessOpportunityName"
          :showArrow="false"
        />

        <LlFormItem
          v-if="form.followUpType !== 3"
          :label="`${titlePrefix}跟进`"
          filed="followUpStatusName"
          :value="form.followUpStatusName"
          @click="_showFollowPicker"
          :rules="[{ required: true, message: `请选择${titlePrefix}跟进` }]"
        />

        <LlFormItem
          v-if="form.followUpType === 3"
          :label="`${titlePrefix}地址`"
          filed="address"
          :value="form.address"
        >
          <template #icon>
            <Icon :name="LocationIcon" />
          </template>
        </LlFormItem>

        <LlFormItem
          v-if="form.followUpType === 3"
          :label="`${titlePrefix}成果`"
          filed="sweepStatus"
          :rules="[{ required: true, message: `请选择${titlePrefix}成果` }]"
          :show-arrow="false"
        >
          <RadioGroup v-model="form.sweepStatus" direction="horizontal">
            <LlRadio :name="1">收获商机</LlRadio>
            <LlRadio :name="2">未收获商机</LlRadio>
          </RadioGroup>
        </LlFormItem>

        <LlFormItem
          v-if="form.followUpType === 3 && form.sweepStatus === 1"
          label="收获商机"
          placehoder="请添加商机"
          :show-arrow="false"
        >
          <template slot="label-right">
            <div
              @click="() => (showBusinessPopup = true)"
              style="color: #1d6fe9"
              class="underline"
            >
              添加商机
            </div>
          </template>
          <div
            class="text-12px px-12px py-11px rounded-8px flex flex-col mb-8px"
            style="background-color: #f3f8fe; color: #333333"
            v-if="form.opportunityList.length"
          >
            <template v-for="(item, index) in form.opportunityList">
              <div
                class="flex items-center justify-between mb-12px last:mb-0"
                :key="item.id"
              >
                <div class="flex-1 flex items-start mr-12px">
                  <span
                    class="bg-black w-15px h-15px text-white rounded-1 p-3px mr-6px flex items-center justify-center"
                  >
                    {{ index + 1 }}
                  </span>
                  <span class="leading-16px flex-1">
                    {{ item.name }}
                  </span>
                </div>
                <Icon
                  :name="DeleteIcon"
                  @click="_commerceRemove(item, index)"
                />
              </div>
            </template>
          </div>
        </LlFormItem>

        <LlFormItem
          :label="`${titlePrefix}结果`"
          filed="followUpResult"
          :show-arrow="false"
          :value="form.followUpResult"
          :rules="[{ required: true, message: `请输入${titlePrefix}结果` }]"
        >
          <Field
            v-model="form.followUpResult"
            rows="3"
            type="textarea"
            autosize
            class="!p-0"
            maxlength="150"
            placeholder="请输入结果"
            show-word-limit
          />
        </LlFormItem>
      </LlForm>
    </div>
    <div class="footer">
      <Button
        class="flex-1 !rounded-10px"
        @click="$router.back()"
        plain
        type="primary"
      >
        取消
      </Button>
      <Button
        @click="handleSave"
        :loading="loading"
        class="flex-1 !ml-9px !rounded-10px"
        type="primary"
      >
        保存
      </Button>
    </div>

    <!-- 跟进结果弹窗 -->
    <Popup v-model="showFollow" round position="bottom">
      <Picker
        :columns="followOptions"
        show-toolbar
        title="跟进结果"
        @cancel="showFollow = false"
        @confirm="
          (item) =>
            _pickerSelect(
              item,
              'followUpStatus',
              'followUpStatusName',
              'showFollow'
            )
        "
      />
    </Popup>

    <!--  -->
    <!-- 添加商机弹窗 -->
    <Popup
      v-model="showBusinessPopup"
      :overlay="false"
      position="right"
      class="w-full h-full overflow-hidden"
    >
      <AddCommerce
        v-if="showBusinessPopup"
        show-uploader
        @cancel="() => (showBusinessPopup = false)"
        @confirm="_commerceConfirm"
      ></AddCommerce>
    </Popup>
  </div>
</template>

<script>
import _ from "lodash";
import {
  Toast,
  Icon,
  Field,
  Button,
  RadioGroup,
  Popup,
  Picker,
  Dialog,
} from "vant";
import LlForm from "@/components/ll-form";
import LlFormItem from "@/components/ll-form-item";
import LlRadio from "@/components/ll-radio";
import AddCommerce from "../components/commerce.vue";

import DateIcon from "@/assets/icon/date.png";
import LocationIcon from "@/assets/icon/location.png";
import DeleteIcon from "@/assets/icon/delete.png";

import { TODO_TYPE } from "@/constants";
import {
  fetchTodoDetail,
  fetchDictOptions,
  fetchTodoFollow,
  fetchBusinessOpportunity,
} from "@/services";

export default {
  components: {
    Icon,
    Field,
    Button,
    RadioGroup,
    Popup,
    Picker,
    LlRadio,
    LlForm,
    LlFormItem,
    AddCommerce,
  },
  data() {
    return {
      DateIcon,
      LocationIcon,
      DeleteIcon,
      loading: false,
      form: {
        todoId: null,
        followUpType: null,
        followUpTypeName: null,
        followUpBeginTime: null,
        followUpEndTime: null,
        businessOpportunityId: null,
        businessOpportunityName: null,
        followUpStatus: null,
        followUpStatusName: null,
        followUpResult: null,
        address: null,
        sweepStatus: null, // 扫街结果
        opportunityList: [], // 扫街商机
      },
      showFollow: false, // 跟进结果
      followOptions: [],
      showBusinessPopup: false, // 扫街添加商机
    };
  },
  computed: {
    titlePrefix() {
      if (this.form.followUpType) {
        const [type] = TODO_TYPE.filter(
          ({ key }) => key === this.form.followUpType
        );
        return type.text;
      } else {
        return "拜访";
      }
    },
    outDate() {
      const { followUpBeginTime, followUpEndTime } = this.form;
      if (followUpBeginTime && followUpEndTime) {
        return [followUpBeginTime, followUpEndTime];
      } else {
        return [];
      }
    },
  },
  created() {
    this._initData();
  },
  methods: {
    _initData() {
      this.form.followUpType = Number(this.$route.query.type);
      this.$nextTick(() => {
        this.handleApplyViews();
      });
    },
    // 获取申请详情
    async handleApplyViews() {
      try {
        const result = await fetchTodoDetail({ todoId: this.$route.query.id });
        const obj = {
          todoId: result.id,
          followUpType: result.todoType,
          followUpTypeName: `外出${this.titlePrefix}`,
          followUpBeginTime: result.clockOnTime,
          followUpEndTime: result.clockOutTime,
          businessOpportunityId: result.businessOpportunityId,
          businessOpportunityName: result.businessOpportunityName,
          followUpStatus: null,
          followUpStatusName: null,
          followUpResult: null,
          address: result.address,
          sweepStatus: null, // 扫街结果
          opportunityList: [], // 扫街商机
        };
        this.form = { ...this.form, ...obj };
      } catch (error) {
        Toast("获取详情失败");
      }
    },
    handleSave: _.throttle(function () {
      this.$refs.form
        .validate()
        .then(async () => {
          try {
            const form = { ...this.form };
            if (
              form.followUpType === 3 &&
              form.sweepStatus === 1 &&
              form.opportunityList.length === 0
            ) {
              Toast("请添加商机");
              return;
            }
            this.loading = true;
            await fetchTodoFollow({ ...form });
            this.$store.commit(`work/${this.$route.query.load}`, {
              value: true,
            });
            Toast("保存成功");
            this.$router.back();
          } catch (error) {
            this.loading = false;
            Toast(error.message || "新增失败");
          }
        })
        .catch((e) => {
          Toast(e[0].message);
        });
    }, 500),
    /**
     * 跟进结果选项
     */
    async _showFollowPicker() {
      try {
        const result = await fetchDictOptions("follow_up_status");
        this.followOptions = result
          .map(({ name, type }) => ({
            text: name,
            key: type,
          }))
          .filter(({ key }) => key !== 0);
        this.$nextTick(() => {
          this.showFollow = true;
        });
      } catch (error) {
        Toast("获取跟进结果选项失败");
      }
    },
    /**
     * 添加商机
     */
    async _commerceConfirm(form, done) {
      try {
        let result = await fetchBusinessOpportunity(form);
        done();
        form.id = result;
        this.form.opportunityList.push(form);
        this.$nextTick(() => {
          this.showBusinessPopup = false;
        });
      } catch (error) {
        done();
        Toast(error.message || "新增失败");
      }
    },
    _commerceRemove(item, index) {
      Dialog.confirm({
        title: "提示",
        message: `确认删除商机【${item.name}】`,
      })
        .then(() => {
          this.form.opportunityList.splice(index, 1);
        })
        .catch(() => {});
    },
    _pickerSelect(val, value, label, model) {
      this.form[value] = val.key;
      this.form[label] = val.text;
      this.$nextTick(() => {
        this[model] = false;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.page-apply {
  @apply flex flex-col;
  .page-form {
    @apply px-10px py-12px flex-1 overflow-auto;
  }
  .footer {
    @apply flex items-center pt-10px px-16px bg-white;
    padding-bottom: calc(env(safe-area-inset-bottom) + 10px);
    box-shadow: 0px -2px 6px 0px rgba(164, 170, 183, 0.2);
  }
}
</style>
